//
//  HPComposedController.swift
//  MyWeibo
//
//  Created by apple on 16/4/21.
//  Copyright © 2016年 Apengpeng. All rights reserved.
//

import UIKit
import SVProgressHUD

class HPComposedController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.greenColor()
        
        setupUI()
        
        registerNotification()
    }

    
    private func setupUI() {
        
        setNavgationBar()
        setTextView()
        setToolBar()
        
        // 设置图片选择控制器
        setPictureSelector()
    }
    
    
    //MARK: 注册通知
    private func registerNotification() {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: 键盘尺寸变化
    @objc private func keyboardWillChange(note: NSNotification) {
        
        let userInfo = note.userInfo!
        // 获取键盘frame 是结构体, 需要转为 NSValue.CGRectValue() 类型
        let rect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        // 自定布局 的页面执行动画
        // 计算 toolBar 的偏移量
        let offsetY = -screenHeight + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offsetY)
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            // 强制刷新
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: 图片选择
    @objc private func selectPicture() {
        
        // 更新图片选择器的约束
        pictureSelector.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(screenHeight / 3 * 2)
        }
        
        print("选择图片")
    }
    
    @objc private func selectEmoticon() {

        print("选择表情")
    }
    
    // MARK: 关闭页面
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
        print("关闭")
    }
    
    //MARK:发送微博
    @objc private func send() {
        
        print("发送微博")
        guard let token = HPUserAccountViewModel.sharedUserAccountViewModel.userAccount?.access_token else {
            SVProgressHUD.showErrorWithStatus("未登录")
            return
        }
        
        HPNetworkingTools.sharedTools.sendStatus(token, status: textView.text, imageList: pictureSelector.imageList) { (result, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            } else {
                SVProgressHUD.showInfoWithStatus("发送成功")
                self.close()
            }
        }
    }
    
    
    // 懒加载图片选择控制器
    private lazy var pictureSelector: HPPictureController = HPPictureController()
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var textView: UITextView = {
       
        let tv = UITextView()
        tv.backgroundColor = UIColor.lightTextColor()
        tv.font = UIFont.systemFontOfSize(16)
        tv.textColor = UIColor.blueColor()
        // 设置代理 
        tv.delegate = self
        
        // 设置可以滚动
        tv.alwaysBounceVertical = true
        
        // 设置textView 
        tv.keyboardDismissMode = .OnDrag
        return tv
    }()
    
    private lazy var placeHolderLabel: UILabel = UILabel(text: "在这里发布微博哦", textColor: UIColor.yellowColor(), fontSzie: 16)
    
    private lazy var rightBarButtonItem: UIBarButtonItem = {
        
        let btn = UIButton()
        btn.setTitle("发送", forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        btn.setTitleColor(UIColor.lightGrayColor(), forState: .Disabled)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
        
        btn.addTarget(self, action: "send", forControlEvents: .TouchUpInside)
        let rightBarButtonItem = UIBarButtonItem(customView: btn)
        return rightBarButtonItem
    }()
}


//MARK: setNavgationBar
extension HPComposedController {
    
    private func setNavgationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "close")
        navigationItem.rightBarButtonItem = rightBarButtonItem
        navigationItem.rightBarButtonItem?.enabled = false
        
        let middView = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 40))
        let titleLabel = UILabel(text: "发布微博", textColor: UIColor.redColor(), fontSzie: 17)
        let nameLabel = UILabel(text: HPUserAccountViewModel.sharedUserAccountViewModel.userAccount!.name!, textColor: UIColor.blueColor(), fontSzie: 13)
        
        middView.addSubview(nameLabel)
        middView.addSubview(titleLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(middView.snp_top)
            make.centerX.equalTo(middView.snp_centerX)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(middView.snp_centerX)
            make.top.equalTo(titleLabel.snp_bottom)
        }
        
        navigationItem.titleView = middView
    }
}


// MARK: TextView
extension HPComposedController {
    
    private func setTextView() {
        
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(screenHeight / 3)
        }
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(7)
            make.left.equalTo(textView)
        }
    }
    

    private func setToolBar() {
        
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(self.view)
        }
        
        // 定义数组
        var toolBarItems: [UIBarButtonItem] = [UIBarButtonItem]()
        let itemsSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background","actionName": "selectPicture"]]
        
        // 遍历settings 创建按钮设置属性
        for itemSetting in itemsSettings {
            if let cationName = itemSetting["actionName"] {
                
                let item = UIBarButtonItem(imageName: itemSetting["imageName"], target: self, action: Selector(cationName))
                toolBarItems.append(item)
        }
            // 添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            toolBarItems.append(space)
        }
        // 移除最后一个弹簧
        toolBarItems.removeLast()
        toolBar.items = toolBarItems
    }
}


// MARK: 监听textView中值的变化
extension HPComposedController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }   
}

// 设置图片选择的界面
extension HPComposedController {
    
    private func setPictureSelector() {
        
        // 添加子视图控制器
        view.addSubview(pictureSelector.view)
        
        // 设置约束
        pictureSelector.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            
            // 设置高度
            make.height.equalTo(0)
        }
    }
}



extension HPComposedController {
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
}
















